package commons.base.httpserver.example;

import java.io.IOException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import commons.base.http.SimpleHttpClient;
import commons.base.httpserver.example.HelloController.TestModel;
import commons.base.util.StringUtil;

public class SpringExample2 {

	public static void main(String[] args) throws IOException {
		TestModel testModel = new TestModel();
    	testModel.setAge(100);
    	testModel.setName("yyyyyyyyyyyyyyyyy");
    	
		String r = SimpleHttpClient
					.newPost("http://localhost:8010/hello/t2")
					.addHeader("Content-Type", "application/json;charset=UTF-8")
					.setBodyString(JSON.toJSONString(testModel))
					.execute(true).getBody();
		
		TestModel testModel2 = parseObject(r, TestModel.class);
		
		System.err.println(r);
		System.err.println(testModel2.getAge());
		System.err.println(testModel2.getName());
	}
	
	public static <T> T parseObject(String text, Class<T> clazz){
//		if(StringUtil.isEmpty(text)){
//			throw new RuntimeException("error: text is empty.");
//		}
		
		JSONObject json = JSON.parseObject(text);
		
		if(json.containsKey("errorCode")){
			throw new RuntimeException("error: " + json.getString("errorMsg"));
		}
		
		return JSON.toJavaObject(json, clazz);
	}

}
